package com.tywj.buscustomerapp.view.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.utils.MD5Utils;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.view.myview.TaylorWebChromeClient;
import com.tywj.buscustomerapp.view.myview.TaylorWebView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class JsWebActivity extends BaseActivity {
    @BindView(R.id.bridge_web)
    TaylorWebView bridgeWebView;
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.head_left)
    ImageView back;
    public static final int REQUEST_SELECT_FILE_CODE = 100;
    private static final int REQUEST_FILE_CHOOSER_CODE = 101;
    private boolean isPaying = false;
    private String od = "";
    private ValueCallback<Uri> mUploadMsg;
    private ValueCallback<Uri[]> mUploadMsgs;
    private String loginpath = "";


    @Override
    protected int getContentId() {
        return R.layout.activity_js_web;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        title.setText("胖哒户外");
        bridgeWebView.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && bridgeWebView.canGoBack()) {
                    bridgeWebView.goBack();
                    return true;
                }
                return false;
            }
        });

        bridgeWebView.setOnLoginListener(new TaylorWebChromeClient.onAlterListener() {
            @Override
            public void onNoLogin(String url) {
                loginpath = url;
                String user =  SPUtils.getUserPhone(JsWebActivity.this);
                if (user!=null && !user.equals("")){
                    doLogin();
                }else{
                    Intent loginIntent = new Intent(JsWebActivity.this,LoginActivity.class);
                    startActivityForResult(loginIntent,20011);
                }
            }
        });

        bridgeWebView.setOpenFileChooserCallBack(new TaylorWebChromeClient.OpenFileChooserCallBack() {
            @Override
            public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMsg = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), REQUEST_FILE_CHOOSER_CODE);
            }

            @Override
            public void showFileChooserCallBack(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (mUploadMsgs != null) {
                    mUploadMsgs.onReceiveValue(null);
                }
                mUploadMsgs = filePathCallback;
                try {
                    Intent intent = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        intent = fileChooserParams.createIntent();
                    }
                    startActivityForResult(intent, REQUEST_SELECT_FILE_CODE);
                } catch (ActivityNotFoundException e) {
                    mUploadMsgs = null;
                }
            }
        });

        bridgeWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.getUrl().toString().equals("http://www.pddaoyou.com/od.html")){
                        finish();
                    }
                    if (request.getUrl().toString().startsWith("weixin://wap/pay?")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(request.getUrl().toString()));
                        isPaying = true;
                        startActivity(intent);
                    }else if (request.getUrl().toString().substring(0,29).equals("http://www.pddaoyou.com/oodd-")){
                        od = request.getUrl().toString();
                        view.loadUrl(od);
                    } else {
                        Map<String, String> extraHeaders = new HashMap<>();
                        extraHeaders.put("Referer", "http://www.pddaoyou.com");
                        view.loadUrl(request.getUrl().toString(), extraHeaders);
                    }
                }
                return true;
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    if (url.equals("http://www.pddaoyou.com/od.html")){
                        finish();
                        return true;
                    }
                    if (url.startsWith("weixin://wap/pay?")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        isPaying = true;
                        startActivity(intent);
                        return true;
                    }else if (url.substring(0,29).equals("http://www.pddaoyou.com/oodd-")){
                        od = url;
                        view.loadUrl(od);
                    } else {
                        Map<String, String> extraHeaders = new HashMap<>();
                        extraHeaders.put("Referer", "http://www.pddaoyou.com");
                        view.loadUrl(url, extraHeaders);
                    }
                    return true;
                }
                return true;
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isPaying && !od.equals("")){
            bridgeWebView.loadUrl(od);
            od="";
        }
        isPaying = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_SELECT_FILE_CODE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (mUploadMsgs == null) {
                        return;
                    }
                    mUploadMsgs.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                    mUploadMsgs = null;
                }
                break;
            case REQUEST_FILE_CHOOSER_CODE:
                if (mUploadMsg == null) {
                    return;
                }
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                mUploadMsg.onReceiveValue(result);
                mUploadMsg = null;
                break;
            case 20011:
                doLogin();
                break;

        }
    }

    private void doLogin(){
        if (loginpath!=null && !loginpath.equals("")) {
            StringBuffer path = new StringBuffer(loginpath.replace(".html","/"));
            String phone = SPUtils.getUserPhone(getApplicationContext());
            path.append(Config.OUT_DOOR_ID).append("-").append(phone).append("-")
                    .append(MD5Utils.strToMd5By32(Config.OUT_DOOR_ID + phone + Config.OUT_DOOR_SECRET));
            bridgeWebView.loadUrl(path.toString());
        }
    }

    @Override
    protected void initData() {
        super.initData();
        if (getIntent()!=null){
            String path = getIntent().getStringExtra("url");
            bridgeWebView.loadUrl(path);
        }
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }




}
